package com.lg.wxq.utils;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.jar.Attributes.Name;

import org.json.JSONObject;

import com.lg.wxq.config.Strings;

public class BeanUtils {
	public static <T> T jsonObjectToBean(Class<T> clazz,JSONObject jsonObject){
		try{
			T newInstance = clazz.newInstance();
			Iterator keys = jsonObject.keys();
			while (keys.hasNext()) {
				String key=(String) keys.next();
				Field name = clazz.getDeclaredField(key);
				name.setAccessible(true);
				String className = name.getType().getName().trim();
				if(Strings.CLASSNAME_STRING.equals(className)){
					name.set(newInstance, jsonObject.getString(key));
				}else if(Strings.CLASSNAME_INT.equals(className)){
					name.setInt(newInstance, jsonObject.getInt(key));
				}else if(Strings.CLASSNAME_LONG.equals(className)){
					name.setLong(newInstance, jsonObject.getLong(key));
				}else if(Strings.CLASSNAME_BOOLEAN.equals(className)){
					name.setBoolean(newInstance, jsonObject.getBoolean(key));
				}else{
					if(!(jsonObject.get(key)+"").equals("null")){
						name.set(newInstance,jsonObjectToBean(Class.forName(className),jsonObject.getJSONObject(key)));
					}
				}
			}
			return newInstance;
		}catch (Exception e) {
			DebugUtils.exception(e);
			return null;
		}
	}
}
